package com.unkow.first.telegram.util;


import static org.cloud.constant.CoreConstant.TEL_VALIDATE_CODE_CACHE_KEY;

import com.unkow.first.telegram.dto.TelValidateCodeCheckDTO;
import com.unkow.first.telegram.dto.TelValidateCodeResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.cloud.context.RequestContextManager;
import org.cloud.core.redis.RedisUtil;
import org.cloud.entity.LoginUserDetails;
import org.cloud.utils.SpringContextUtil;
import org.springframework.context.annotation.Lazy;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;

/**
 * telegram 消息发送工具类，用通用的内置消息机器人发送
 */
@Slf4j
public final class TelValidateCodeUtil {

    private final TelegramLongPollingBot telegramBot;

    @Lazy
    private TelValidateCodeUtil() {
        telegramBot = SpringContextUtil.getBean("telegramLongPollingBot", TelegramLongPollingBot.class);
    }

    private final static TelValidateCodeUtil handler = new TelValidateCodeUtil();

    public static TelValidateCodeUtil single() {
        return handler;
    }

    public boolean checkValidateCode(TelValidateCodeCheckDTO checkDTO) {
        String cacheKey = String.format(TEL_VALIDATE_CODE_CACHE_KEY, checkDTO.getValidateCodeKey());
        TelValidateCodeResultDTO codeResultDTO = RedisUtil.single().get(cacheKey);
        boolean isMatch = codeResultDTO != null && codeResultDTO.getValidateValue().equalsIgnoreCase(checkDTO.getValidateValue());
        isMatch = isMatch && codeResultDTO.getOperate().equals(checkDTO.getOperate());
        if (!isMatch) {
            return false;
        }
        if (checkDTO.getOperate().isMustLogin) {
            LoginUserDetails loginUserDetails = RequestContextManager.single().getRequestContext().getUser();
            isMatch = loginUserDetails != null && loginUserDetails.getId().equals(codeResultDTO.getUserId());
        }
        if (isMatch) {
            RedisUtil.single().remove(cacheKey);
        }
        return isMatch;
    }

}


